<template>
    <div class="l7-map">
        <div class="btns">
            <!-- 添加图层 -->
            <el-button style="z-index: 10;opacity: 0.8;" type="primary" @click="addLayers">添加图层</el-button>

            <!-- 选择城市图层 -->
            <el-select @change="handleCityChange">
                <el-option v-for="item in cityList" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
            </el-select>
        </div>

        <div id="map"></div>

    </div>
</template>

<script setup lang="ts">
import MapPopop from '@/components/MapPopop.vue'
import { Scene, LineLayer, PointLayer, RasterLayer, PolygonLayer, HeatmapLayer, Zoom, Popup, LayerPopup, MouseLocation, LayerSwitch, MapTheme, ImageLayer, CityBuildingLayer } from '@antv/l7';
import { Map, Mapbox } from '@antv/l7-maps';
import mapboxgl from 'mapbox-gl'

const cityList = [
    { label: '孝感', value: 'xiaogan.json' },
    { label: '江苏', value: 'jiangsu.json' },
    // {label: '广州', value: 'guangzhou'},
]

const layerList: any = []
let layerSwitch: LayerSwitch = new LayerSwitch({
    multiple: true,
});


const handleCityChange = (val: string) => {
    fetch('/mapjson/' + val)
        .then((res) => res.json())
        .then((data) => {
            let exist = scene.getLayerByName(val)
            if (exist) {
                scene.removeLayer(exist)
            }

            // const layer = new PointLayer({ name: val }).source(data, { parser: { type: 'geojson' } }).shape('simple').color('#006dff').style({ opacity: 0.5, }).active(true).size(20);
            const layer = new PolygonLayer({ name: val }).source(data, { parser: { type: 'geojson' } }).shape('water').color('#006dff').style({ opacity: 0.5, })
            // const layer = new HeatmapLayer({ name: val }).source(data)



            setTimeout(() => {
                scene.addLayer(layer);

                // 如果有该图层 先移除
                let has = layerList.findIndex((item: any) => item.name === val)
                if (has !== -1) {
                    layerList.splice(has, 1)
                }
                layerList.push({
                    name: val,
                    layer
                })
                const layerPopup = new LayerPopup({
                    items: [
                        {
                            layer: val,
                            // fields: [
                            //     {
                            //         field: 'name',
                            //         formatValue: (name?: string) => {
                            //             debugger
                            //             return val
                            //         }
                            //     },
                            // ],
                            title: val + 1,
                            customContent: (item: any) => {
                                // debugger
                                return `<div style="width: 100px; height: 100px; color: red;">${val}</div>`
                            }
                        },
                    ],
                    trigger: 'hover',
                });


                layerSwitch.setOptions({
                    layers: layerList.map((item: any) => item.layer),

                })

                scene.addPopup(layerPopup);

                const layer2 = new ImageLayer({});
                layer2.source('https://gw.alipayobjects.com/zos/rmsportal/FnHFeFklTzKDdUESRNDv.jpg', {
                    parser: {
                        type: 'image',
                        // extent: [121.168, 30.2828, 121.384, 30.4219],
                        coordinates: [[60.2191, 50.2202],
                        [117.2191, 50.2202],
                        [117.2191, 30.2202],
                        [80.2191, 20.2202]]


                    },
                }).style({ opacity: 0.5, })

                scene.addLayer(layer2)

                layer.on('click', (e: any) => {

                    popup.setOptions({
                        title: '666',
                        html: `<div style='color:red'>${val}</div>`,
                        lngLat: {
                            lng: e.lngLat.lng,
                            lat: e.lngLat.lat,
                        },
                    })
                    scene.addPopup(popup)
                })
            }, 500);

        })
}

const popup: Popup = new Popup({

})

popup.on('open', () => {
    ElMessage.info('添加弹窗')
})

popup.on('hide', () => {
    ElMessage.info({
        grouping: true,
        message: '关闭弹窗',
    })

})

let scene: Scene | any = null;

const initScene = () => {
    mapboxgl.accessToken = 'dsadsad'
    const mapsss = new mapboxgl.Map({
        container: 'map', // container id
        style: {
            version: 8,
            sources: {
                m_mono: {
                    type: 'raster',
                    tiles: ['/tile/{z}/{x}/{y}.png'],
                    tileSize: 256,
                    attribution: '',
                },
            },
            // glyphs: '../../static/glyphs/{fontstack}/{range}.pbf',
            layers: [
                {
                    id: 'm_mono',
                    type: 'raster',
                    source: 'm_mono',
                    minzoom: 0,
                    maxzoom: 18,
                },
            ],
        },
        center: [114.297, 35.586], // starting position [lng, lat]
        zoom: 2.2, // starting zoom
        projection: 'globe',
        // pitch: 90
    });


    scene = new Scene({
        id: 'map',
        logoVisible: false,
        // map: new Map({
        //     zoom: 1,
        //     minZoom: 1,
        //     maxZoom: 18,
        //     center: [114.297, 30.586],
        //     projection: 'globe',

        // }),

        // 使用指定的mapsss
        map: new Mapbox({
            mapInstance: mapsss,
        }),
    });

    scene.on('loaded', () => {
        // 手动添加地图底图
        // const layer = new RasterLayer();
        // layer.source(
        //     '/tile/{z}/{x}/{y}.jpg',
        //     {
        //         parser: {
        //             type: 'rasterTile',
        //             tileSize: 256,
        //             minZoom: 1,
        //             maxZoom: 18,
        //         },
        //     },
        // )
        // scene.addLayer(layer);
        const zoom = new Zoom({
            position: 'topright',
            className: 'my-test-class',
            showZoom: true,
        });

        const mouseLocation = new MouseLocation({
            position: 'bottomright',
        });

        // 主题组件
        // const mapTheme = new MapTheme()

        // 将实例化的控件添加至 L7 中
        scene.addControl(mouseLocation);

        // scene.addControl(mapTheme);


        scene.addControl(zoom);

        scene.addControl(layerSwitch);

        scene.addPopup(popup)

        fetch('https://gw.alipayobjects.com/os/rmsportal/ggFwDClGjjvpSMBIrcEx.json')
            .then((res) => res.json())
            .then((data) => {
                const layer = new CityBuildingLayer({
                    zIndex: 999,
                    name: 'city'
                });
                layer.source(data);
                scene.addLayer(layer);
                layerSwitch.setOptions({ layers: [layer] })
            });
    });

    scene.on('style.load', () => {
        scene.map.setFog({
            color: "rgb(186, 210, 235)",
            "high-color": "rgb(36, 92, 223)",
            "horizon-blend": 0.02,
            "space-color": "rgb(11, 11 ,25)",
            "star-intensity": 0.6,
        });
    })

    // scene.on('click', (e: any) => {
    //     const comp: any = createApp(MapPopop, {
    //         infos: {
    //             lngLat: e.lngLat,
    //             point: e.point,
    //         }
    //     })
    //     const div = document.createElement('div')
    //     div.className = 'aaa bbb'
    //     comp.mount(div)
    //     popup.setLngLat(e.lngLat).setHTML(div).panToPopup()


    // })
}

const addLayers = () => {
    // 添加线图层
    const layer = new LineLayer()
        .source(
            {
                type: 'FeatureCollection',
                features: [
                    {
                        type: 'Feature',
                        properties: {},
                        geometry: {
                            type: 'LineString',
                            coordinates: [
                                [106.5234375, 57.51582286553883],
                                [136.40625, 61.77312286453146],
                                [116.40625, 65.77312286453146],
                                [96.40625, 61.77312286453146],
                            ],
                        },
                    },
                ],
            }
        )
        .size(1)
        .shape('line')
        .active(true)
        .color('#f00')
        .animate({
            enable: true,
            interval: 1,
            duration: 1,
            trailLength: 200,
            speed: 0.5,

        });

    scene.addLayer(layer);
}

// 添加点图层

onMounted(() => {
    initScene();
})
</script>


<style lang="less" scoped>
.l7-map {
    position: relative;
    height: 100%;
    width: 100%;
    overflow: hidden;

    .btns {
        width: 100%;
        display: flex;
        position: absolute;
        top: 10px;
        left: 10px;
        z-index: 10;

        .el-select {
            width: 10%;
        }
    }

    #map {
        height: 100%;
        width: 100%;

    }
}
</style>